package com.l.d.app.library.app;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import com.l.d.app.library.R;

import skin.support.app.SkinCompatActivity;

/**
 * Created by 林德 on 2017/4/12 15:06.
 * <p/>
 */
public abstract class FragActivity extends SkinCompatActivity
{
    private static final String TAG_FRAGMENT = FragActivity.class.getName() + "/TAG_FRAGMENT";
    private static final String TAG_BUNDLE = FragActivity.class.getName() + "/TAG_BUNDLE";

    @Override
    protected final void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_wrap_frag);
        final Intent intent = getIntent();
        initFragment(intent);
    }

    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        setIntent(intent);
        initFragment(intent);
    }

    private void initFragment(Intent intent)
    {
        String fragmentTag = null;
        Bundle bundle = null;
        if (intent != null)
        {
            fragmentTag = intent.getStringExtra(TAG_FRAGMENT);
            bundle = intent.getBundleExtra(TAG_BUNDLE);
        }
        Fragment fragment = fragment(fragmentTag);
        if (fragment != null)
        {
            if (bundle != null)
            {
                fragment.setArguments(bundle);
            }
            getSupportFragmentManager().beginTransaction().replace(R.id.wrap_fragment_activity, fragment).commit();
        }
    }

    protected abstract Fragment fragment(@Nullable String fragmentTag);

    public static <T extends FragActivity> void start(@NonNull Class<T> cls, @NonNull Context context, @NonNull String fragmentTag)
    {
        start(cls, context, fragmentTag, null);
    }

    public static <T extends FragActivity> void start(@NonNull Class<T> cls, @NonNull Context context, @NonNull String fragmentTag, @Nullable Bundle bundle)
    {
        Intent intent = new Intent(context, cls);
        intent.putExtra(TAG_FRAGMENT, fragmentTag).putExtra(TAG_BUNDLE, bundle);
        context.startActivity(intent);
    }
}
